<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>发布者订阅者模式之封装</title>
</head>
<body>
	<h1>发布者订阅者模式之封装</h1>
</body>
<script type="text/javascript">
    
    const event = {
        list:[],
        listen:function(key,fn){//添加订阅者
            if(!this.list[key]){
                this.list[key] = [];
            }

            this.list[key].push(fn)
        },
        trigger:function(){//发布消息
            var key = Array.prototype.shift.call(arguments);
            var fns = this.list[key];
            if(!fns || fns.length == 0){
                return ;
            }

            for(var i=0,fn;fn = fns[i++];){
                fn.apply(this,arguments)
            }
        },
        remove:function(key,fn){//删除订阅者
            var fns = this.list[key];
            if(!fns){
                return false;
            }
            if(!fn){
                // fn && (fns.length = 0);
                this.list[key] = []
            }else{
                for(var i=fns.length-1;i>=0;i--){
                    var _fn = fns[i];
                    if(_fn == fn){
                        fns.splice(i,1)
                    }
                }
            }
        }
    }

    var initEvent = function(obj) {
        for(var i in event) {
            obj[i] = event[i];
        }
    };

    var shoeObj = {};
    initEvent(shoeObj);

    var f1 = function(somethings){
        console.log(`pink喜欢${somethings}`)
    }
    var f2 = function(somethings){
        console.log(`red喜欢${somethings}`)
    }

    shoeObj.listen('pink',f1)

    shoeObj.listen('red',f2)

    shoeObj.remove('pink',f1)
    shoeObj.trigger('pink','肉肉')
    shoeObj.trigger('red','蔬菜')

</script>
</html>